package cn.tmpan.project.service.impl;

import cn.tmpan.project.common.PublicMethod;
import cn.tmpan.project.common.ServerResponse;
import cn.tmpan.project.model.CacheDataConfig;
import cn.tmpan.project.dao.CacheDataConfigMapper;
import cn.tmpan.project.model.vo.CacheDataVo;
import cn.tmpan.project.service.ICacheDataConfigService;
import cn.tmpan.project.utils.DateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AutoGenerator
 */
@Service
public class CacheDataConfigServiceImpl extends ServiceImpl<CacheDataConfigMapper, CacheDataConfig> implements ICacheDataConfigService {

    @Autowired
    private CacheDataConfigMapper cacheDataConfigMapper;

    @Override
    public String getKey(String keys) {
        if (StringUtils.isEmpty(keys)) {
            return null;
        }
        LambdaQueryWrapper<CacheDataConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CacheDataConfig::getCacheKey, keys);
        CacheDataConfig sysCacheConfig = cacheDataConfigMapper.selectOne(queryWrapper);
        if (sysCacheConfig == null) {
            return null;
        }
        if (sysCacheConfig.getType().equals(0)) {
            return sysCacheConfig.getCacheValue();
        }
        if (sysCacheConfig.getExpiredTime().getTime() < System.currentTimeMillis()) {
            /**
             *@desc 缓存已过期  删除key
             */
            int res = cacheDataConfigMapper.delete(queryWrapper);
            if (res > 0) {
                return null;
            }
            throw new RuntimeException("keys is have,but is Expired,del keys is error! ");
        }
        return sysCacheConfig.getCacheValue();
    }


    @Override
    public void setKey(String keys, String val, Integer second) {
        this.setKeys(keys, val, this.checkout(keys, val), second);
    }


    @Override
    public void setKey(String keys, String val) {
        this.setKeys(keys, val, this.checkout(keys, val), null);
    }


    @Override
    public ServerResponse getKeyExpires(String keys) {
        if (StringUtils.isEmpty(keys)) {
            return ServerResponse.createByErrorMessage("缓存不存在");
        }
        LambdaQueryWrapper<CacheDataConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CacheDataConfig::getCacheKey, keys);
        /**
         *@desc 判断KEY是否存在
         */
        CacheDataConfig sysCacheConfig = cacheDataConfigMapper.selectOne(queryWrapper);
        if (sysCacheConfig == null) {
            return ServerResponse.createByErrorMessage("暂无缓存");
        }
        if (sysCacheConfig.getExpiredTime().getTime() < System.currentTimeMillis()) {
            /**
             *@desc 缓存已过期  删除key
             */

            int res = cacheDataConfigMapper.delete(queryWrapper);
            if (res > 0) {
                return ServerResponse.createByErrorMessage("缓存已过期");
            }
            throw new RuntimeException("keys is have,but is Expired,del keys is error! ");
        }
        HashMap hashMap = new HashMap(16);
        hashMap.put("keys", keys);
        hashMap.put("val", sysCacheConfig.getCacheValue());
        // 返回剩余时间 单位/秒
        hashMap.put("laveTimeSeconds", DateTimeUtil.laveTime(sysCacheConfig.getExpiredTime()));
        return ServerResponse.createBySuccess(hashMap);
    }

    @Override
    public ServerResponse listByAll() {
        final IPage<CacheDataConfig> cacheDataConfigIPage = cacheDataConfigMapper.selectListByXml(new Page());
        return ServerResponse.createBySuccess(cacheDataConfigIPage);
    }

    @Override
    public ServerResponse listByAll(Integer pageNum, Integer pageSize, String orderBy, Boolean desc) {
        Page<CacheDataConfig> cacheDataConfigPage = new Page<>();
        cacheDataConfigPage.setCurrent(pageNum);
        cacheDataConfigPage.setSize(pageSize);
        if (!StringUtils.isEmpty(orderBy)) {
            if (desc) {
                cacheDataConfigPage.setDesc(orderBy);
            } else {
                cacheDataConfigPage.setAsc(orderBy);
            }
        }

        final IPage<CacheDataConfig> cacheDataConfigIPage = cacheDataConfigMapper.selectListByXml(cacheDataConfigPage);
        return ServerResponse.createBySuccess(cacheDataConfigIPage);

    }

    @Override
    public ServerResponse listByAll(Integer pageNum, Integer pageSize, String orderBy) {
        PublicMethod.initPageHelp(pageNum, pageSize, orderBy);
        List<CacheDataConfig> cacheDataConfigList = cacheDataConfigMapper.selectListByXml();
        return ServerResponse.createBySuccess(PublicMethod.getPageInfo(cacheDataConfigList));

    }

    @Override
    public ServerResponse listByAllAndVo(Integer pageNum, Integer pageSize, String orderBy) {
        PublicMethod.initPageHelp(pageNum, pageSize, orderBy);
        List<CacheDataConfig> cacheDataConfigList = cacheDataConfigMapper.selectListByXml();
        return ServerResponse.createBySuccess(PublicMethod.getPageInfo(cacheDataConfigList, this.getCacheDataListVo(cacheDataConfigList)));
    }

    /**
     * 处理需要格式化list的分页
     *
     * @param cacheDataConfigs
     * @return
     */
    private List<CacheDataVo> getCacheDataListVo(List<CacheDataConfig> cacheDataConfigs) {
        List<CacheDataVo> cacheDataConfigVoList = new ArrayList<>(10);
        cacheDataConfigs.forEach(o -> {
            CacheDataVo cacheDataVo = new CacheDataVo();
            cacheDataVo.setCacheDataConfig(o);
            cacheDataVo.setVal(o.getCacheValue());
            cacheDataConfigVoList.add(cacheDataVo);
        });
        return cacheDataConfigVoList;
    }


    /**
     * 校验参数
     *
     * @param keys
     * @param val
     * @return
     */
    private CacheDataConfig checkout(String keys, String val) {
        if (StringUtils.isEmpty(keys)) {
            throw new RuntimeException("keys is null !");
        }
        if (StringUtils.isEmpty(val)) {
            throw new RuntimeException("value is null !");
        }
        LambdaQueryWrapper<CacheDataConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CacheDataConfig::getCacheKey, keys);
        return cacheDataConfigMapper.selectOne(queryWrapper);
    }

    /**
     * 设置keys
     *
     * @param keys
     * @param val
     * @param sysCacheConfig
     * @param second
     */
    private void setKeys(String keys, String val, CacheDataConfig sysCacheConfig, Integer second) {
        if (sysCacheConfig != null) {
            /**
             *@desc key已经存在 更新key
             */
            sysCacheConfig.setCacheValue(val);
            if (second == null) {
                sysCacheConfig.setType(0);
            } else {
                sysCacheConfig.setType(1);
            }
            sysCacheConfig.setExpiredTime(new Date());
            LambdaUpdateWrapper<CacheDataConfig> configLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            configLambdaUpdateWrapper.eq(CacheDataConfig::getCacheKey, keys);
            if (cacheDataConfigMapper.update(sysCacheConfig, configLambdaUpdateWrapper) > 0) {
                return;
            }
            throw new RuntimeException("keys is have,but update database value is error!");
        }
        sysCacheConfig = new CacheDataConfig();
        if (second == null) {
            sysCacheConfig.setType(0);
        } else {
            sysCacheConfig.setType(1);
        }
        sysCacheConfig.setCacheKey(keys);
        sysCacheConfig.setCacheValue(val);
        sysCacheConfig.setExpiredTime(new Date());
        if (cacheDataConfigMapper.insert(sysCacheConfig) > 0) {
            return;
        }
        throw new RuntimeException("keys is not have,but update database value is error!");
    }
}
